<template>
	<view class="player-detail">
		<xjx-clipper v-if="visible" :image-url="src" @success="cropCallback" @cancel="visible = false"
			:width="size.width" :height="size.height" :is-limit-move="true" :is-show-photo-btn="false"
			:is-show-rotate-btn="false" :max-ratio="1.5"></xjx-clipper>
		<view v-if="formInfo.icon&&!formInfo.icon.includes('player-icon-')" @click="chooseCropImage" class="icon-box">
			<image :src="formInfo.icon" mode=""></image>
		</view>
		<view v-else @click="chooseCropImage" class="icon-box">
			<image v-if="formInfo.sex==2" :src="'@/static/images/mine/player-icon-gril-grey.png'|addBaseImgUrl" mode="">
			</image>
			<image v-else :src="'@/static/images/mine/player-icon-boy-grey.png'|addBaseImgUrl" mode=""></image>
		</view>
		<view class="icon-edit" @click="chooseCropImage">
			编辑头像
		</view>
		<view class="row-item flex-box">
			<view class="label must">
				姓名
			</view>
			<input type="text" maxlength="16" placeholder="请输入姓名" v-model="formInfo.relName" />
		</view>
		<view class="row-item flex-box">
			<view class="label must">
				联系电话
			</view>
			<input type="text" maxlength="11" placeholder="请输入联系人电话" v-model="formInfo.mobile" />
		</view>
		<view class="row-item">
			<view class="label">
				性别
			</view>
			<view class="value-box flex-box sex">
				<view @click="sexHandle('1')" :class="formInfo.sex==1?'checked':''">
					男生
				</view>
				<view @click="sexHandle('2')" :class="formInfo.sex==2?'checked':''">
					女生
				</view>
			</view>
		</view>
		<view class="row-item flex-box">
			<view class="label must">
				出生日期
			</view>
			<view @click="showPopup" class="right flex-box birthday">
				<input type="text" readonly placeholder="请输入出生日期" :value="formInfo.birthday" />
				<van-icon :name="'../../../../static/images/icon-calendar-little.png'|addBaseImgUrl" size="15px" />
			</view>
		</view>
		<view class="row-item">
			<view class="label">
				与会员关系
			</view>
			<view class="value-box flex-box">
				<view @click="typeHandle('1')" :class="formInfo.type==1?'checked':''">
					本人
				</view>
				<view @click="typeHandle('2')" :class="formInfo.type==2?'checked':''">
					子女
				</view>
				<view @click="typeHandle('3')" :class="formInfo.type==3?'checked':''">
					伴侣
				</view>
				<view @click="typeHandle('4')" :class="formInfo.type==4?'checked':''">
					朋友
				</view>
				<view @click="typeHandle('5')" :class="formInfo.type==5?'checked':''">
					其他
				</view>
			</view>
		</view>
		<view class="row-item">
			<view class="label-row flex-box">
				<view class="label">
					球员级别
					<text>（请参考等级说明选择）</text>
				</view>
				<view @click="showLevelPopup" class="introduction">
					<van-icon :name="'@/static/images/mine/icon-important.png'|addBaseImgUrl" size="15px" />
					<text>等级说明</text>
				</view>
			</view>
			<view class="qydengji">
				<!-- <slider block-size="24" min="1" max="9" block-color="#2E87FF" activeColor="#2E87FF"></slider> -->
				<van-slider @change="changeDrag('change', $event)" @drag="changeDrag('drag', $event)" :value="formInfo.skillLevel" :step="1" :min="1" :max="9"
					:minValue="minValue" :maxValue="maxValue" bar-height="2px"></van-slider>
			</view>
			<view class="qyts">
				请参考等级说明选择，该级别将作为您报名课程或活动时供俱乐部参考的级别
			</view>
		</view>
		<view class="row-item flex-box">
			<view class="label">
				设置默认球员
			</view>
			<view class="right-switch">
				<uni-switch size="25" active-color="#09B501" v-model="formInfo.isDefault"></uni-switch>
			</view>
		</view>
		<view class="btn-area">
			<text v-if="id" @click="makeSureDelete" class="btn-delete">
				删除球员信息
			</text>
			<view @click="submit" class="save-btn">
				保存
			</view>
		</view>
		<!-- 弹出框 -->
		<van-dialog id="van-dialog" confirm-button-color="#2E87FF" cancel-button-color="#2E87FF" />
		<!-- 下拉选择 -->
		<van-popup :show="popupShow" position="bottom" custom-style="height:55%;padding-top:20rpx;">
			<van-datetime-picker type="date" :value="defalutDate" @cancel="popupCancel" @confirm="popupConfirm"
				:max-date="maxDate" :min-date="minDate" />
		</van-popup>
		<!-- 球员级别说明popup -->
		<van-popup round
		           :show="levelPopupShow"
		           position="bottom"
		           custom-style="height: 610px;"
		           @close="closeLevelPopup"
		           closeable>
		  <view class="hypopup">
		    <text class="tit">L1-L9球员等级说明</text>
				<view class="content">
					<view class="col666 flex">
					  <view class="left-label">业余1级：</view><view>初学者，能把球打过网</view>
					</view>
					<view class="col666 flex">
					  <view class="left-label">业余2级：</view><view>了解基本规则和基本动作，但很不稳定</view>
					</view>
					<view class="col666 flex">
					  <view class="left-label">业余3级：</view><view>熟悉基本规则和基本动作，发力掌握不好，不会反手，步法较乱</view>
					</view>
					<view class="col666 flex">
					  <view class="left-label">业余4级：</view><view>技术动作比较熟练，高远球能到后场，掌握反手动作，熟悉基础步法</view>
					</view>
					<view class="col666 flex">
					  <view class="left-label">业余5级：</view><view>能应用部分高级技术如假动作、勾对角，攻防质量较高，初步控制场上局势</view>
					</view>
					<view class="col666 flex">
					  <view class="left-label">业余6级：</view><view>技术掌握全面，有一定战术意识，步法较娴熟，较好控制场上局势</view>
					</view>
					<view class="col666 flex">
					  <view class="left-label">业余7级：</view><view>很强的攻防能力，熟练应用各种高级技战术，能及时调整战术和心态</view>
					</view>
					<view class="col666 flex">
					  <view class="left-label">业余8级：</view><view>经常取得大型业余比赛前三名，具备和专业退役运动员的对抗能力</view>
					</view>
					<view class="col666 flex">
					  <view class="left-label">业余9级：</view><view>专业退役运动员</view>
					</view>
				</view>
		    <van-button @click="closeLevelPopup"
		                round
		                type="info"
		                custom-style="height:88rpx;margin:0 30rpx;display:block;line-height:88rpx">知道了</van-button>
		  </view>
		</van-popup>
		<van-toast id="van-toast" />
	</view>
</template>

<script>
	let maxDate = new Date().getTime() - (1000 * 60 * 60 * 24)
	let defalutDate = new Date('2000/01/01').getTime()
	let minDate = new Date().getTime() - (1000 * 60 * 60 * 24 * 365 * 100)
	import xjxClipper from '@/components/xjx-clipper/index'
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'
	import {
		dateUtils,
		strUtils,
		isEmojiCharacter,
		checkNormalName
	} from '@/common/js/util.js'
	import Dialog from '@/wxcomponents/vant/dist/dialog/dialog';
	import Toast from '@/wxcomponents/vant/dist/toast/toast';
	import {
		baseImgUrl
	} from '@/common/js/config'
	export default {
		components: {
			xjxClipper
		},
		data() {
			return {
				id: '',
				formInfo: {
					relName: '',
					mobile: '',
					icon: '',
					isDefault: false,
					sex: '1',
					type: '1',
					birthday: '2000-01-01',
					skillLevel: '1'
				},
				switchChecked: false,
				imgs: [], //本地图片地址数组
				isChangeIcon: false,
				maxDate: maxDate,
				minDate: minDate,
				defalutDate: defalutDate,
				popupShow: false,
				levelPopupShow: false,
				minValue: 'L1',
				maxValue: 'L9',
				// -------------------------------------
				src: null, // 裁剪图片地址 rpx
				visible: false, // 是否显示
				size: { //裁剪尺寸
					width: 650,
					height: 650
				},
				result: '', //裁剪结果地址
				tapFlag: true
			};
		},
		onLoad(data) {
			if (data.id) {
				this.id = data.id
				this.init()
			}
			this.select = data.select || null
			this.formInfo.mobile = this.userInfo.mobile
		},
		computed: {
			...mapState(['userInfo', 'accessToken']),
		},
		methods: {
			cropCallback(e) {
				this.visible = false
				this.upImgs(e.url)
			},
			chooseCropImage() {
				let _this = this;
				uni.chooseImage({
					count: 1,
					success(res) {
						_this.visible = true
						_this.src = res.tempFilePaths[0]
					}
				})
			},
			async init() {
				const param = {
					'ACCESS-TOKEN': this.accessToken
				}
				const res = await this.$api.getPlayerDetail(param, this.id)
				if (res && res.code == 200) {
					let b = res.data.isDefault == 1 ? true : false
					res.data.isDefault = b
					this.formInfo = res.data;
					this.minValue = `L${res.data.skillLevel}`;
				}
			},
			changeDrag(action, e) {
        let target = ''
        if (action === 'change') {
          target = e.detail
        } else {
          target = e.target.value
        }
				this.minValue = `L${target}`
				this.formInfo.skillLevel = target;
				if (target == 9) {
					this.maxValue = ''
				} else {
					this.maxValue = 'L9'
				}
			},
			switchChange(e) {
				this.switchChecked = e.detail ? '1' : '0'
			},
			sexHandle(n) {
				this.formInfo.sex = n
			},
			typeHandle(n) {
				this.formInfo.type = n
			},
			showPopup() {
				this.popupShow = true
			},
			popupCancel() {
				this.popupShow = false
			},
			popupConfirm(e) {
				this.popupShow = false
				this.formInfo.birthday = dateUtils.stampFormat(e.detail)
			},
			showLevelPopup(){
				this.levelPopupShow = true
			},
			closeLevelPopup(){
				this.levelPopupShow = false
			},
			//添加上传图片
			chooseImageTap() {
				let _this = this;
				uni.showActionSheet({
					itemList: ['从相册中选择', '拍照'],
					itemColor: "#00000",
					success: function(res) {
						if (!res.cancel) {
							if (res.tapIndex == 0) {
								_this.chooseWxImage('album')
							} else if (res.tapIndex == 1) {
								_this.chooseWxImage('camera')
							}
						}
					}
				})
			},
			// 图片本地路径
			chooseWxImage(type) {
				let _this = this;
				let imgsPaths = _this.imgs;
				uni.chooseImage({
					sizeType: ['original', 'compressed'],
					sourceType: [type],
					success: function(res) {
						_this.upImgs(res.tempFilePaths[0], 0) //调用上传方法
					}
				})
			},
			//上传服务器
			upImgs(imgurl, index) {
				let _this = this;
				this.$api.uploadImage({
					'ACCESS-TOKEN': this.accessToken,
					'imgurl': imgurl
				}).then(res => {
					if (res && res.code == 200) {
						_this.formInfo.icon = res.data[0].imgNetworkAddress
						_this.isChangeIcon = true
					}
				})
			},
			makeSureDelete() {
				if (this.id) {
					Dialog.confirm({
							title: '确认删除球员信息？',
							cancelButtonText: '取消',
							width: '325px',
							messageAlign: 'left',
							customStyle: 'border-radius:7.5px;',
							className: 'my-dialog-confirm'
						})
						.then(() => {
							// on confirm
							this.deletePlayer()
						})
						.catch(() => {
							// on cancel

						})
				}
			},
			async deletePlayer() {
				const param = {
					'ACCESS-TOKEN': this.accessToken
				}
				const res = await this.$api.deletePlayer(param, this.id)
				if (res && res.code == 200) {
					let timer = setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
						clearTimeout(timer)
					}, 1500)
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				}else if(res.code == 500){
					Toast({
						message:"为了保障您已购课程及活动正常使用，已下单球员不能删除哦！",
						duration: 2000,
					})
				}else{
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				}
				
			},
			async submit() {
				if (!this.tapFlag) {
					return false
				}
				const param = {
					'ACCESS-TOKEN': this.accessToken,
					...this.formInfo
				}
				param.isDefault = param.isDefault ? '1' : '0'
				let iconUrl = param.icon
				if (iconUrl) {
					param.icon = 'images/' + iconUrl.split('/images/')[1]
				}
				if (!param.relName) {
					uni.showToast({
						title: '请输入球员姓名',
						icon: 'none'
					})
				} else if (param.relName && param.relName.trim().length>8) {
					uni.showToast({
						title: '球员姓名不能超过8个字符',
						icon: 'none'
					})
				} else if (param.relName && !checkNormalName(param.relName.trim())) {
					uni.showToast({
						title: '球员姓名不能有特殊符号',
						icon: 'none'
					})
				} else if (!param.mobile) {
					uni.showToast({
						title: '请输入联系电话',
						icon: 'none'
					})
				} else if (!strUtils.isMobilePhoneNum(param.mobile)) {
					uni.showToast({
						title: '请输入正确格式的联系电话',
						icon: 'none'
					})
				} else if (!param.birthday) {
					uni.showToast({
						title: '请输入出生日期',
						icon: 'none'
					})
				} else {
					if (!param.icon || param.icon.includes('player-icon-')) {
						if (param.sex == 1) {
							param.icon = 'images/' + baseImgUrl.split('/images/')[1] + 'mine/player-icon-boy.png'
						} else {
							param.icon = 'images/' + baseImgUrl.split('/images/')[1] + 'mine/player-icon-gril.png'
						}
					}
					let res = {}
					this.tapFlag = false
					if (this.id) {
						res = await this.$api.updatePlayer(param)
					} else {
						res = await this.$api.addPlayer(param)
					}
					if (res && res.code == 200) {
						let pages = getCurrentPages()
						let [pagesIndex, pagesLength] = ['', pages.length]
						if (this.select && !this.id) {
							let obj = res.data.filter((item) => {
								return item.isNew == '1'
							})[0]

							pages.map((item, index) => {
								if (item.route.includes('confirmOrder/confirmOrder')) {
									pagesIndex = index
								}
							})
							pages[pagesIndex].$vm.setqydata(res.data, obj)
						}
						let timer = setTimeout(() => {
							uni.navigateBack({
								delta: this.select && !this.id ? (pagesLength - 1 - pagesIndex) : 1
							})
							clearTimeout(timer)
						}, 1500)
					}
					this.tapFlag = true
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.van-slider__button {
		background: url('@/static/images/icon_huakuai.png') no-repeat center;
		background-color: #2E87FF !important;
		background-size: 16rpx 19rpx;
	}

	.player-detail {
		overflow: hidden;
		padding: 0 30rpx;

		.icon-box {
			// border: 10rpx solid rgb(224, 237, 255);
			border-radius: 50%;
			margin: 30rpx auto 0;
			overflow: hidden;
			width: 173rpx;
			height: 173rpx;
			box-sizing: content-box;

			image {
				width: 100%;
				height: 100%;
				vertical-align: middle;
			}
		}
		
		.icon-edit{
			color: $bg-color-blue1;
			font-size: 28rpx;
			margin: 30rpx auto 0;
			text-align: center;
			width: 130rpx;
			line-height: 28rpx;
		}

		.row-item {
			border-bottom: 1rpx solid #E9E9E9;
			padding: 30rpx 0;

			&.flex-box {
				align-items: center;
			}

			.label-row {
				align-items: center;
			}

			.label {
				line-height: 50rpx;
				font-size: 30rpx;
				padding-left: 24rpx;
				position: relative;
				white-space: nowrap;
				text {
					font-size: 26rpx;
					color: #CCCCCC;
				}

				&.must:before {
					content: '*';
					color: $text-color-red1;
					position: absolute;
					top: 50%;
					transform: translateY(-50%);
					left: 0;
				}
			}

			.introduction {
				display: flex;
				align-items: center;

				text {
					color: #FDB42E;
					font-size: 26rpx;
					margin-left: 10rpx;
				}
			}

			.value-box {
				margin: 20rpx 0 10rpx;

				view {
					height: 78rpx;
					text-align: center;
					line-height: 78rpx;
					border: 2rpx solid #CCCCCC;
					border-radius: 15rpx;
					flex: 1 0 auto;

					&+view {
						margin-left: 20rpx;
					}
				}

				.checked {
					border-color: $public-color-blue1;
					color: $public-color-blue1;
				}
			}

			.right {
				align-items: center;
			}

			input {
				text-align: right;
			}

			.birthday {
				input {
					margin-right: 20rpx;
					pointer-events: none;
				}
			}

			.qydengji {
				padding: 60rpx 12px 20rpx;
				margin-top: 20rpx;
			}
			.qyts{
				color: #999999;
				font-size: 26rpx;
				padding: 20rpx 22rpx 0 22rpx;
				text-align: justify;
			}

		}

		.btn-area {
			text-align: center;
			padding-top: 40rpx;

			.btn-delete {
				color: $public-color-blue1;
				margin: 40rpx auto;
			}

			.save-btn {
				margin: 40rpx 0;
				height: 88rpx;
				background-color: $public-color-blue1;
				line-height: 88rpx;
				border-radius: 44rpx;
				color: $text-color-white1;
			}
		}
		
	}
	
	.hypopup {
	  padding: 40rpx 0 30rpx;
	  .tit {
	    font-size: 36rpx;
	    color: #333;
	    display: block;
	    text-align: center;
	    margin-bottom: 30rpx;
	  }
		.content{
			padding: 0 50rpx;
			.col666 {
			  font-size: 28rpx;
			  color: #666;
			  margin-bottom: 16rpx;
			  display: block;
			}
			.col999 {
			  font-size: 26rpx;
			  color: #999;
			  line-height: 40rpx;
			}
			.flex {
			  display: flex;
				.left-label{
					min-width: 140rpx;
				}
			}
			margin-bottom: 60rpx;
		}
	}
</style>
<style>
	.van-picker-column__item {
		line-height: 44px !important;
	}
</style>
